package com.isunland.managesystem.ui;

import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.NavUtils;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.ButterKnife;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseVolleyActivity;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.CurrentUser;
import com.isunland.managesystem.entity.DataStatus;
import com.isunland.managesystem.entity.RProInvoiceRecdSub;
import com.isunland.managesystem.entity.ReceiptDetailLab;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.utils.LogUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.SharedPreferencesUtil;
import com.isunland.managesystem.utils.ToastUtil;
import java.util.HashMap;
import java.util.UUID;
import org.json.JSONException;

public class ReceiptDetailFragment extends Fragment {

  public static final String EXTRA_RECEIPT_DETAIL_ID =
      "com.isunland.managesystem.ui.ReceiptDetailFragment.EXTRA_RECEIPT_DETAIL_ID";
  public static final String EXTRA_DATA_STATUS =
      "com.isunland.managesystem.ui.ReceiptDetailFragment.EXTRA_DATA_STATUS";
  @BindView(R.id.tv_goodsName_receiptDetail) EditText mGoodsNameEt;// 商品名称
  @BindView(R.id.tv_modelType_receiptDetail) EditText mModelTypeEt;// 规格型号.
  @BindView(R.id.tv_unit_receiptDetail) EditText mUnitEt;// 单位
  @BindView(R.id.et_unitPrice_receiptDetail) EditText mUnitPriceEt;// 单价.
  @BindView(R.id.et_amount_receiptDetail) EditText mAmountEt;// 数量
  @BindView(R.id.tv_amountOfMoney_receiptDetail) TextView mMoneyTv;// 金额
  @BindView(R.id.et_taxRate_receiptDetail) EditText mTaxRateEt;// 税率
  @BindView(R.id.tv_salesTax_receiptDetail) TextView mSalesTaxTv;// 销项税.
  @BindView(R.id.tv_salesMoney_receiptDetail) TextView mSalesMoneyTv;// 销项额
  private BaseVolleyActivity mActivity;
  private RProInvoiceRecdSub mReceiptDetail;
  private int mPosition;
  private String dataStatus = "";

  public static ReceiptDetailFragment newInstance(String receptDetailId) {
    Bundle args = new Bundle();
    args.putString(EXTRA_RECEIPT_DETAIL_ID, receptDetailId);
    ReceiptDetailFragment fragment = new ReceiptDetailFragment();
    fragment.setArguments(args);
    return fragment;
  }

  public static ReceiptDetailFragment newInstance(String receptDetailId, String dataStatus) {
    Bundle args = new Bundle();
    args.putString(EXTRA_RECEIPT_DETAIL_ID, receptDetailId);
    args.putString(EXTRA_DATA_STATUS, dataStatus);
    ReceiptDetailFragment fragment = new ReceiptDetailFragment();
    fragment.setArguments(args);
    return fragment;
  }

  @Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setHasOptionsMenu(true);
    ((BaseVolleyActivity) getActivity()).getSupportActionBar().setTitle(R.string.receiptDetail);
    mActivity = (BaseVolleyActivity) getActivity();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
      if (NavUtils.getParentActivityName(getActivity()) != null) {

        ((BaseVolleyActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
      }
    }
  }

  @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.fragment_receipt_detail, container, false);
    //        findViews(v);
    ButterKnife.bind(this, v);
    initData();
    return v;
  }

  /**
   * Find the Views in the layout<br />
   * <br />
   * Auto-created on 2016-01-26 13:13:46 by Android Layout Finder
   * (http://www.buzzingandroid.com/tools/android-layout-finder)
   */
  //    private void findViews(View v) {
  //
  //        mGoodsNameEt = (EditText) v.findViewById(R.id.tv_goodsName_receiptDetail);
  //        mModelTypeEt = (EditText) v.findViewById(R.id.tv_modelType_receiptDetail);
  //        mUnitEt = (EditText) v.findViewById(R.id.tv_unit_receiptDetail);
  //        mUnitPriceEt = (EditText) v.findViewById(R.id.et_unitPrice_receiptDetail);
  //        mAmountEt = (EditText) v.findViewById(R.id.et_amount_receiptDetail);
  //        mMoneyTv = (TextView) v.findViewById(R.id.tv_amountOfMoney_receiptDetail);
  //        mTaxRateEt = (EditText) v.findViewById(R.id.et_taxRate_receiptDetail);
  //        mSalesTaxTv = (TextView) v.findViewById(R.id.tv_salesTax_receiptDetail);
  //        mSalesMoneyTv = (TextView) v.findViewById(R.id.tv_salesMoney_receiptDetail);
  //    }
  private void initData() {
    dataStatus = getArguments().getString(EXTRA_DATA_STATUS);
    String receiptDetailId = getArguments().getString(EXTRA_RECEIPT_DETAIL_ID);
    //添加明细时,id为空,需要初始化数据.
    if (receiptDetailId == null) {
      mReceiptDetail = new RProInvoiceRecdSub();
      mReceiptDetail.setId(UUID.randomUUID().toString());
      String id =
          SharedPreferencesUtil.getString(getActivity(), SharedPreferencesUtil.RECEIPT_ID, "");
      mReceiptDetail.setMainId(id);
      mReceiptDetail.setMemberCode(CurrentUser.newInstance(getActivity()).getMemberCode());
    } else {
      mReceiptDetail = ReceiptDetailLab.get(getActivity()).getItem(receiptDetailId);
      // mReceiptDetail = (RProInvoiceRecdSub)
      // getArguments().getSerializable(EXTRA_RECEIPT_DETAIL);
      // mPosition=getArguments().getInt(EXTRA_POSITION);
      mGoodsNameEt.setText(mReceiptDetail.getMaterialName());
      mModelTypeEt.setText(mReceiptDetail.getMtype());
      //        mModelTypeEt.setText(mReceiptDetail.getMtype());
      mUnitEt.setText(mReceiptDetail.getMunit());
      mUnitPriceEt.setText(MyUtils.doubleToStr(mReceiptDetail.getMprice()));
      mAmountEt.setText(MyUtils.doubleToStr(mReceiptDetail.getMnumber()));
      mTaxRateEt.setText(MyUtils.doubleToStr(mReceiptDetail.getMtaxRate()));
      mMoneyTv.setText(MyUtils.doubleToStr(mReceiptDetail.getMsumPrice()));
      mSalesTaxTv.setText(MyUtils.doubleToStr(mReceiptDetail.getOutputTax()));
      mSalesMoneyTv.setText(MyUtils.doubleToStr(mReceiptDetail.getMtsumPrice()));
    }

    mUnitPriceEt.addTextChangedListener(new TextWatcher() {

      @Override public void onTextChanged(CharSequence s, int start, int before, int count) {

        try {
          String text = s.toString();
          Double price = Double.parseDouble(text);
          mReceiptDetail.setMprice(price);
          calculateNumber();
        } catch (Exception e) {
          // Auto-generated catch block
          e.printStackTrace();
        }
      }

      @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        // Auto-generated method stub

      }

      @Override public void afterTextChanged(Editable s) {
        // Auto-generated method stub

      }
    });

    mAmountEt.addTextChangedListener(new TextWatcher() {

      @Override public void onTextChanged(CharSequence s, int start, int before, int count) {
        try {
          String text = s.toString();
          Double amount = Double.parseDouble(text);
          mReceiptDetail.setMnumber(amount);
          calculateNumber();
        } catch (Exception e) {
          // Auto-generated catch block
          e.printStackTrace();
        }
      }

      @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        // Auto-generated method stub

      }

      @Override public void afterTextChanged(Editable s) {
        // Auto-generated method stub

      }
    });
    mTaxRateEt.addTextChangedListener(new TextWatcher() {

      @Override public void onTextChanged(CharSequence s, int start, int before, int count) {
        // Auto-generated method stub
        try {
          String text = s.toString();
          Double taxRate = Double.parseDouble(text);
          mReceiptDetail.setMtaxRate(taxRate);
          calculateNumber();
        } catch (Exception e) {
          // Auto-generated catch block
          e.printStackTrace();
        }
      }

      @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        // Auto-generated method stub

      }

      @Override public void afterTextChanged(Editable s) {
        // Auto-generated method stub

      }
    });

    if (dataStatus.equals(DataStatus.WAIT_CHECK) || dataStatus.equals(DataStatus.CHECK_PASS)) {
      mUnitPriceEt.setEnabled(false);
      mAmountEt.setEnabled(false);
      mTaxRateEt.setEnabled(false);
    }
  }

  /**
   * 计算其他字段值, 计算方式为:单价*个数=金额 (金额*税率)%100=销项税. 金额-销项税=销项额.
   */
  private void calculateNumber() {
    Double price = mReceiptDetail.getMprice();
    Double amount = mReceiptDetail.getMnumber();
    Double taxRate = mReceiptDetail.getMtaxRate();

    // 计算
    Double totalPrice = price * amount;//金额 不含税=数量*单价
    //		Double salesTax = (totalPrice * taxRate) / 100;
    //		Double salesPrice = totalPrice - salesTax;
    Double salesTax = totalPrice * (taxRate / 100);//税=金额*税率
    Double salesPrice = totalPrice + salesTax;//含税金额=金额+税
    //四舍五入保留两位小数
    //salesPrice = NumberUtil.roundTwo(salesPrice);
    //salesTax = NumberUtil.roundTwo(salesTax);
    //        totalPrice=NumberUtil.roundTwo(totalPrice);
    // 赋值
    mReceiptDetail.setMsumPrice(salesPrice);
    mReceiptDetail.setMtsumPrice(totalPrice);
    mReceiptDetail.setOutputTax(salesTax);

    // 显示.
    mMoneyTv.setText(MyUtils.doubleToStr(mReceiptDetail.getMsumPrice()));
    mSalesTaxTv.setText(MyUtils.doubleToStr(mReceiptDetail.getOutputTax()));
    mSalesMoneyTv.setText(MyUtils.doubleToStr(mReceiptDetail.getMtsumPrice()));
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    if (dataStatus.equals(DataStatus.NEW) || dataStatus.equals(DataStatus.ABORT)) {
      inflater.inflate(R.menu.menu_save_delete, menu);
    } else {
      super.onCreateOptionsMenu(menu, inflater);
    }
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case android.R.id.home:

        if (NavUtils.getParentActivityName(getActivity()) != null) {
          NavUtils.navigateUpFromSameTask(getActivity());
        }

        break;
      // 保存
      case R.id.menu_item_save:
        String name = mGoodsNameEt.getText().toString().trim();
        String type = mModelTypeEt.getText().toString().trim();
        String unit = mUnitEt.getText().toString().trim();
        String price = mUnitPriceEt.getText().toString().trim();
        String amount = mAmountEt.getText().toString().trim();
        String rate = mTaxRateEt.getText().toString().trim();

        if (TextUtils.isEmpty(name)
            || TextUtils.isEmpty(type)
            || TextUtils.isEmpty(unit)
            || TextUtils.isEmpty(price)
            || TextUtils.isEmpty(amount)
            || TextUtils.isEmpty(rate)

            ) {
          ToastUtil.show(R.string.notComplete);
          return true;
        }

        mReceiptDetail.setMaterialName(name);
        mReceiptDetail.setMtype(type);
        mReceiptDetail.setMunit(unit);
        //添加
        if (ReceiptDetailLab.get(getActivity()).getItem(mReceiptDetail.getId()) == null) {

          ReceiptDetailLab.get(getActivity()).getList().add(mReceiptDetail);
        }
        ReceiptDetailLab.get(getActivity()).setUnsaved(true);
        getActivity().setResult(Activity.RESULT_OK);
        getActivity().finish();

        break;
      // 启动流程

      // 删除.
      case R.id.menu_item_delete:

        volleyPostDelete();

        break;

      default:
        break;
    }
    return super.onOptionsItemSelected(item);
  }

  //    private boolean isEmptyEditText(EditText et) {
  //        String str=et.getText().toString().trim();
  //        return TextUtils.isEmpty(str);
  //
  //    }

  private void volleyPostDelete() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_RECEIPT_DETAIL_DELETE);
    HashMap<String, String> params = new HashMap<>();
    params.put("id", mReceiptDetail.getId());
    MyUtils.showDialogLoading(getActivity(), R.string.loadingDelete);
    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {

        MyUtils.dismissDialog();
        try {

          SuccessMessage successsMessage = new Gson().fromJson(arg0, SuccessMessage.class);

          String successType = successsMessage.getResult();

          if (successType.equals("1")) {
            ToastUtil.show(R.string.deleteSuccess);
            ReceiptDetailLab.get(getActivity()).remove(mReceiptDetail.getId());
            getActivity().setResult(Activity.RESULT_OK);
            getActivity().finish();
          } else {
            ToastUtil.show(R.string.deleteFail);
          }
        } catch (Exception e) {
          LogUtil.e("error", e);
          ToastUtil.show(R.string.deleteFail);
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {
        // Auto-generated method stub

      }
    });
  }
}
